<template>
  <div v-loading="loadingAll">
    <div class="addbut">
      <div>
        <el-button
          type="text"
          size="small"
          @click="createVersion(serviceName)"
          icon="document-add"
          >新增版本</el-button
        >
      </div>
      <div style="display: flex" v-if="!!versions.length">
        <div class="select-webkitdirectory">
          <el-button
            size="small"
            @click="onUploadChange"
            type="text"
            icon="UploadFilled"
            >上传文件夹</el-button
          >
          <input
            ref="fileFolder"
            @change="uploadChange"
            name="fileFolder"
            type="file"
            webkitdirectory
          />
        </div>
        <el-upload
          class="upload-demo"
          multiple
          action="#"
          :http-request="(context) => uploadFile(serviceName, context)"
          :show-file-list="false"
        >
          <el-button id="uploadbtn" size="small" type="text" icon="UploadFilled"
            >上传文件</el-button
          >
        </el-upload>
      </div>
    </div>
    <div class="flex-c">
      <div class="flex-left" v-if="versions.length">
        <div
          :class="{ active: currentVersion == item.name, 'flex-sb': true }"
          v-for="(item, index) in versions"
          :key="index"
        >
          <div @click="toDetail(serviceName, item.name, '')">
            {{ item.name }}
          </div>
          <el-button
            @click="runFromVersion(serviceName, item.name)"
            type="text"
            icon="CaretRight"
            size="mini"
          >
            运行
          </el-button>
          <el-button
            @click="deleteVersion(serviceName, item.name)"
            type="text"
            size="mini"
            class="red"
            icon="delete"
          >
            删除
          </el-button>
        </div>
      </div>
      <div class="flex-mian">
        <el-table
          v-loading="loading"
          :data="data"
          style="width: 100%"
          size="mini"
        >
          <el-table-column prop="name" label="文件名">
            <template #default="scope">
              <div
                class="mian-name next"
                v-if="scope.row.isDirectory"
                @click="
                  toDetail(serviceName, currentVersion, scope.row.fullName)
                "
              >
                <el-icon><folder /></el-icon><span>{{ scope.row.name }}</span>
              </div>
              <div
                class="mian-name next"
                v-else
                @click="
                  toDelete(serviceName, currentVersion, scope.row.fullName)
                "
              >
                <el-icon> <document /></el-icon
                ><span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="length"
            label="大小"
            :formatter="lengthFormat"
            width="100"
          />
          <el-table-column prop="lastWriteTime" label="修改日期" width="140" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, ref, getCurrentInstance } from "vue";
import { ElMessageBox } from "element-plus";
export default {
  name: "",
  props: {
    serviceName: String,
  },
  watch: {
    serviceName: {
      deep: true,
      immediate: true,
      handler(serviceName) {
        if (!serviceName) return;
        this.currentVersion = "";
        this.loadVersion(serviceName);
      },
    },
  },
  setup(props) {
    const { proxy } = getCurrentInstance();
    const fileFolder = ref(null);
    const state = reactive({
      loading: false,
      loadingAll: false,
      versions: [],
      data: [],
      currentVersion: "",
      currentPath: "",
    });
    const reLoad = (serviceName) => {
      return toDetail(
        serviceName,
        state.currentVersion,
        state.currentPath,
        true
      );
    };

    const toDetail = (serviceName, version, path, reload) => {
      if (
        state.currentVersion == version &&
        state.currentPath == path &&
        !reload
      )
        return;
      state.loading = true;
      $.get(`api/file/lookFiles/${serviceName}/${version}`, {
        path: path,
      })
        .then((r) => {
          if (path) {
            let ps = path.split("/");
            let fullName = ps.slice(0, ps.length - 1).join("/");
            r.data.unshift({
              isDirectory: true,
              name: "返回上级",
              fullName: fullName,
            });
          }
          state.data = r.data;
          state.currentVersion = version;
          state.currentPath = path;
        })
        .finally(() => (state.loading = false));
    };
    const loadVersion = (serviceName, version) => {
      $.get("/api/file/getVersion", { serviceName }).then((r) => {
        state.versions = r.data;
        state.data = [];
        if (version) {
          toDetail(serviceName, version, "");
        } else if (r.data.length) {
          toDetail(serviceName, r.data[0].name, "");
        }
      });
    };
    return {
      fileFolder,
      ...toRefs(state),
      lengthFormat(row) {
        const ut = ["B", "KB", "MB", "GB", "TB"];
        if (row.length == null) return "";
        let length = row.length;
        let i = 0;
        while (length > 1024) {
          length = parseInt(length / 1024);
          i++;
        }
        return length + ut[i];
      },
      onUploadChange() {
        fileFolder.value.click();
      },
      createVersion(serviceName) {
        ElMessageBox.confirm("确认添加版本", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }).then(() => {
          $.get("api/file/CreateVersion", { serviceName }).then((r) => {
            loadVersion(serviceName);
          });
        });
      },
      filterFileName(file) {
        let lastModified = parseInt(file.lastModified / 1000);
        var a = proxy.data.some(
          (a) =>
            a.name == file.name &&
            parseInt(Date.dateParse(a.lastWriteTime).getTime() / 1000) >=
              lastModified
        );
        return !a && !file.name.includes(".pdb");
      },
      uploadChange(e) {
        let serviceName = proxy.serviceName;
        var files = e.target.files;
        if (!files.length) return;
        let arr = [...files].filter(this.filterFileName);
        if (arr.length == 0) {
          ElMessageBox.alert("无差异文件");
          return;
        }
        state.loading = true;
        e.target.value='';
        Promise.each(
          arr.map(
            (file) =>
              function () {
                let i = file.webkitRelativePath.indexOf("/");
                let path =
                  state.currentPath +
                  file.webkitRelativePath.substr(
                    i,
                    file.webkitRelativePath.length - file.name.length - i
                  );
                return $.upload(
                  `/api/file/upload/${serviceName}/${state.currentVersion}?path=${path}&t=${file.lastModified}`,
                  file
                );
              }
          )
        )
          .then((r) => {
            reLoad(serviceName);
          })
          .finally(() => (state.loading = false));
      },
      uploadFile(serviceName, context) {
        state.loading = true;
        $.upload(
          `/api/file/upload/${serviceName}/${state.currentVersion}?path=${state.currentPath}`,
          context.file
        )
          .then((r) => {
            reLoad(serviceName);
          })
          .finally(() => (state.loading = false));
      },
      runFromVersion(serviceName, vname) {
        state.loadingAll = true;
        $.get("/api/guardian/runFromVersion", {
          serviceName: serviceName,
          version: vname,
        })
          .then((r) => {
            proxy.$emit("runFromVersion");
          })
          .finally(() => (state.loadingAll = false));
      },
      deleteVersion(serviceName, vname) {
        ElMessageBox.confirm("确认删除", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }).then((r) => {
          $.get("/api/file/DeleteVersion", {
            serviceName: serviceName,
            versionName: vname,
          }).then((r) => {
            loadVersion(serviceName, r.data);
          });
        });
      },
      loadVersion,
      toDetail,
      toDelete(serviceName, currentVersion, fullName) {
        ElMessageBox.confirm("确认删除", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }).then((r) => {
          state.loading = true;
          $.get(`/api/file/deleteFile/${serviceName}/${currentVersion}`, {
            fullName,
          })
            .then((r) => {
              reLoad(serviceName);
            })
            .finally(() => (state.loading = false));
        });
      },
    };
  },
};
</script>
<style scoped>
.mian-name {
  display: flex;
  align-items: center;
  cursor: default;
}
.mian-name.next {
  cursor: pointer;
}
.mian-name.next:hover {
  color: #1283ba;
}
.mian-name span {
  margin-left: 5px;
}
.red {
  color: red;
}
.addbut {
  display: flex;
  justify-content: space-between;
  position: relative;
  margin-bottom: 10px;
}

.flex-left {
  margin-right: 20px;
  width: 200px;
  height: 440px;
  overflow-x: hidden;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
}

.flex-sb {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 12px;
  box-shadow: inset 0px -1px 0px 0px rgb(227 233 237 / 50%);
}
.flex-sb:hover {
  background: #f5f7fa;
  color: #003e59;
}
.flex-sb:last-of-type {
  box-shadow: none;
}
.flex-sb.active {
  color: #409eff !important;
}
.flex-sb:hover div {
  cursor: pointer;
}
.flex-sb.active:hover div {
  cursor: default;
}
.flex-sb div {
  flex-grow: 1;
}
.flex-c {
  display: flex;
  align-items: flex-start;
}
.flex-mian {
  height: 440px;
  overflow-y: scroll;
  overflow-x: auto;
  flex-grow: 1;
  border: 1px solid #e0e0e0;
}
.select-webkitdirectory {
  margin-right: 20px;
}
.select-webkitdirectory input[type="file"] {
  display: none;
}
</style>
